﻿using HalconDotNet;
using LeaderCCSLaserUI.Data;
using LeaderCCSLaserUI.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using OxyPlot.Axes;
using Prism.Commands;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media;
using System.Xml.Linq;
using ViewROI;
using MessageBox = System.Windows.Forms.MessageBox;

namespace LeaderCCSLaserUI.ViewModels.Dialogs
{
    public class VisionProgramDialogViewModel : DialogViewModel
    {
        #region 变量
        private string partNum = string.Empty;
        private readonly IDialogService _dialogService;
        private HObject mImage;
        #endregion
        #region 属性
        private HImage cameraImage0;
        public HImage CameraImage0
        {
            get { return cameraImage0; }
            set { SetProperty(ref cameraImage0, value); }
        }
        private HObject cameraAppendHObject0;
        public HObject CameraAppendHObject0
        {
            get { return cameraAppendHObject0; }
            set { SetProperty(ref cameraAppendHObject0, value); }
        }
        private Tuple<string, object> cameraGCStyle0;
        public Tuple<string, object> CameraGCStyle0
        {
            get { return cameraGCStyle0; }
            set { SetProperty(ref cameraGCStyle0, value); }
        }
        private ObservableCollection<ROI> cameraROIList0 = new ObservableCollection<ROI>();
        public ObservableCollection<ROI> CameraROIList0
        {
            get { return cameraROIList0; }
            set { SetProperty(ref cameraROIList0, value); }
        }

        private HMsgEntry cameraAppendHMessage0;
        public HMsgEntry CameraAppendHMessage0
        {
            get { return cameraAppendHMessage0; }
            set { SetProperty(ref cameraAppendHMessage0, value); }
        }
        private ObservableCollection<VisionProgramDisp> programList = new ObservableCollection<VisionProgramDisp>();
        public ObservableCollection<VisionProgramDisp> ProgramList
        {
            get { return programList; }
            set { SetProperty(ref programList, value); }
        }
        private bool isReady;
        public bool IsReady
        {
            get { return isReady; }
            set { SetProperty(ref isReady, value); }
        }
        private VisionProgramDisp curProgram;
        public VisionProgramDisp CurProgram
        {
            get { return curProgram; }
            set { SetProperty(ref curProgram, value); }
        }
        private ObservableCollection<VisionProjectDisp> projectList = new ObservableCollection<VisionProjectDisp>();
        public ObservableCollection<VisionProjectDisp> ProjectList
        {
            get { return projectList; }
            set { SetProperty(ref projectList, value); }
        }
        #endregion
        #region 方法绑定
        private DelegateCommand<object> programListSelectCommand;
        public DelegateCommand<object> ProgramListSelectCommand =>
            programListSelectCommand ?? (programListSelectCommand = new DelegateCommand<object>(ExecuteProgramListSelectCommand));
        private DelegateCommand<object> addFunctionCommand;
        public DelegateCommand<object> AddFunctionCommand =>
            addFunctionCommand ?? (addFunctionCommand = new DelegateCommand<object>(ExecuteAddFunctionCommand));
        private DelegateCommand<object> projectPreviewMouseDoubleClickCommand;
        public DelegateCommand<object> ProjectPreviewMouseDoubleClickCommand =>
            projectPreviewMouseDoubleClickCommand ?? (projectPreviewMouseDoubleClickCommand = new DelegateCommand<object>(ExecuteProjectPreviewMouseDoubleClickCommand));
        private DelegateCommand openImageCommand;
        public DelegateCommand OpenImageCommand =>
            openImageCommand ?? (openImageCommand = new DelegateCommand(ExecuteOpenImageCommand));
        private DelegateCommand executeOperateCommand;
        public DelegateCommand ExecuteOperateCommand =>
            executeOperateCommand ?? (executeOperateCommand = new DelegateCommand(ExecuteExecuteOperateCommand));
        private DelegateCommand programManageCommand;
        public DelegateCommand ProgramManageCommand =>
            programManageCommand ?? (programManageCommand = new DelegateCommand(ExecuteProgramManageCommand));
        private DelegateCommand<object> deleteFunctionCommand;
        public DelegateCommand<object> DeleteFunctionCommand =>
            deleteFunctionCommand ?? (deleteFunctionCommand = new DelegateCommand<object>(ExecuteDeleteFunctionCommand));
        private DelegateCommand retateImageCommand;
        public DelegateCommand RetateImageCommand =>
            retateImageCommand ?? (retateImageCommand = new DelegateCommand(ExecuteRetateImageCommand));

        void ExecuteRetateImageCommand()
        {
            if (CameraImage0 != null)
            {
                HOperatorSet.RotateImage(CameraImage0, out mImage, 90, "constant");
                CameraImage0 = new HImage(mImage.CopyObj(1, -1));
            }
            else
            {
                MessageBox.Show("图像不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteDeleteFunctionCommand(object obj)
        {
            if (obj != null)
            {
                if (obj is VisionProjectDisp selectProject)
                {
                    try
                    {
                        if (MessageBox.Show($"确认删除\"{selectProject.Name}\"功能吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                        {
                            using var mdb = new MDbContext(partNum);
                            var projects = mdb.VisionProjects.Where(project => project.ProgramId == CurProgram.Id && project.PcsOrder > selectProject.PcsOrder);
                            {
                                projects.ToList().ForEach(project =>
                                {
                                    project.PcsOrder -= 1;
                                });
                            }
                            mdb.Database.ExecuteSqlRaw($"DELETE FROM VisionProjects WHERE Id = {selectProject.Id}");
                            mdb.SaveChanges();
                            LoadProject(partNum, CurProgram.Id);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show("未选择任何项目", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteProgramManageCommand()
        {
            DialogParameters param = new DialogParameters();
            param.Add("PartNum", partNum);
            _dialogService.ShowDialog("ProgramManageDialog", param, arg =>
            {
                CameraAppendHObject0 = null;
                CameraImage0 = null;
                CameraAppendHMessage0 = null;
                mImage = null;
                ProjectList.Clear();
                LoadProgram(partNum);
                IsReady = false;
            });
        }
        void ExecuteExecuteOperateCommand()
        {
            if (CameraImage0 != null)
            {
                try
                {
                    CameraAppendHMessage0 = null;
                    CameraAppendHObject0 = null;
                    HObject eImage = mImage.CopyObj(1, -1);
                    HTuple row = new HTuple(0), column = new HTuple(0), angle = new HTuple(0), score = new HTuple(0), v1 = new HTuple(0), v2 = new HTuple(0);
                    HObject ngRegion, SelectedRegion;
                    HOperatorSet.GenEmptyObj(out ngRegion);
                    HOperatorSet.GenEmptyObj(out SelectedRegion);
                    foreach (var item in ProjectList)
                    {
                        using var mdb = new MDbContext(partNum);
                        var _function = mdb.VisionFunctions.FirstOrDefault(func => func.Id == item.FunctionId);
                        if (_function != null)
                        {
                            var r = MFunc.FunDictionary[_function.Name].Run(ref eImage, item.Parameter, ref row, ref column, ref angle, ref score, ref ngRegion, ref SelectedRegion, ref v1, ref v2);
                            if (r)
                            {
                                CameraGCStyle0 = new Tuple<string, object>("Color", "spring green");
                                CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                                CameraAppendHObject0 = SelectedRegion.CopyObj(1, -1);
                                item.Result = DispReuslt.Pass;
                            }
                            else
                            {
                                CameraGCStyle0 = new Tuple<string, object>("Color", "red");
                                CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                                CameraAppendHObject0 = ngRegion.CopyObj(1, -1);
                                item.Result = DispReuslt.Ng;
                            }

                            //switch (_function.Name)
                            //{
                            //    case "PreProcessing":
                            //        {
                            //            MFunc.FunDictionary["PreProcessing"].Run(ref eImage, item.Parameter, ref row, ref column, ref angle, ref score, ref ngRegion, ref SelectedRegion);
                            //            CameraImage0 = new HImage(eImage.CopyObj(1, -1));
                            //            item.Result = DispReuslt.Pass;
                            //        }
                            //        break;
                            //    case "ShapeModel":
                            //        {
                            //            MFunc.FunDictionary["ShapeModel"].Run(ref eImage, item.Parameter, ref row, ref column, ref angle, ref score, ref ngRegion, ref SelectedRegion);
                            //            if (score.Length > 0)
                            //            {
                            //                CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                            //                CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                            //                CameraAppendHObject0 = SelectedRegion.CopyObj(1, -1);
                            //                //CameraAppendHMessage0 = new HMsgEntry($"分数:{score.D * 100:f0}\nRow:{row.D:f0}\nColumn:{column.D:f0}\nAngle:{angle.TupleDeg().D:f1}", 10, 10, "magenta", "window", "box", "false", 24, "mono", "true", "false");
                            //                item.Result = DispReuslt.Pass;
                            //            }
                            //            else
                            //            {
                            //                //CameraAppendHMessage0 = new HMsgEntry($"NG", 40, 40, "orange red", "window", "box", "false", 24, "mono", "true", "false");
                            //                item.Result = DispReuslt.Ng;
                            //            }
                            //        }
                            //        break;
                            //    case "BlobCircle":
                            //        {
                            //            MFunc.FunDictionary["BlobCircle"].Run(ref eImage, item.Parameter, ref row, ref column, ref angle, ref score, ref ngRegion, ref SelectedRegion);
                            //            HOperatorSet.CountObj(SelectedRegion, out var hv_Number);
                            //            if ((int)(new HTuple(hv_Number.TupleEqual(1))) != 0)
                            //            {
                            //                CameraGCStyle0 = new Tuple<string, object>("Color", "spring green");
                            //                CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                            //                CameraAppendHObject0 = SelectedRegion.CopyObj(1, -1);
                            //                item.Result = DispReuslt.Pass;
                            //            }
                            //            else
                            //            {
                            //                CameraGCStyle0 = new Tuple<string, object>("Color", "red");
                            //                CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                            //                CameraAppendHObject0 = ngRegion.CopyObj(1, -1);
                            //                item.Result = DispReuslt.Ng;
                            //            }
                            //        }
                            //        break;
                            //    default:
                            //        break;
                            //}
                        }
                        else
                        {
                            MessageBox.Show($"未知方法:{item.FunctionId}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            break;
                        }
                        
                    }
                    CameraAppendHMessage0 = new HMsgEntry($"Row:{row.D:f0}\nColumn:{column.D:f0}\nAngle:{angle.TupleDeg().D:f1}", 10, 10, "magenta", "window", "box", "false", 24, "mono", "true", "false");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("图像不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteOpenImageCommand()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Image Files|*.png;*.bmp;*.jpg;*.tif";
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (mImage != null)
                {
                    mImage.Dispose();
                }
                HOperatorSet.ReadImage(out mImage, openFileDialog.FileName);
                CameraImage0 = new HImage(mImage.CopyObj(1, -1));
            }
        }
        void ExecuteProjectPreviewMouseDoubleClickCommand(object obj)
        {
            if (obj is VisionProjectDisp project)
            {        
                switch (project.Name)
                {
                    case "BlobCircle":
                        {
                            DialogParameters param = new DialogParameters();
                            param.Add("Parameter", project.Parameter);
                            param.Add("Image", mImage);
                            _dialogService.ShowDialog("FunctionBlobCircleDialog", param, arg => {
                                if (arg.Result == ButtonResult.Yes)
                                {
                                    try
                                    {
                                        string paramer = arg.Parameters.GetValue<string>("Parameter");
                                        project.Parameter = paramer;
                                        using var mdb = new MDbContext(partNum);
                                        var _mParam = mdb.VisionProjects.FirstOrDefault(m => m.Id == project.Id);
                                        if (_mParam != null)
                                        {
                                            _mParam.Parameter = paramer;
                                            mdb.SaveChanges();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }

                                }
                            });
                        }
                        break;
                    case "PreProcessing":
                        {
                            DialogParameters param = new DialogParameters();
                            param.Add("Parameter", project.Parameter);
                            param.Add("Image", mImage);
                            _dialogService.ShowDialog("FunctionPreProcessingDialog", param, arg => {
                                if (arg.Result == ButtonResult.Yes)
                                {
                                    try
                                    {
                                        string paramer = arg.Parameters.GetValue<string>("Parameter");
                                        project.Parameter = paramer;
                                        using var mdb = new MDbContext(partNum);
                                        var _mParam = mdb.VisionProjects.FirstOrDefault(m => m.Id == project.Id);
                                        if (_mParam != null)
                                        {
                                            _mParam.Parameter = paramer;
                                            mdb.SaveChanges();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }

                                }
                            });
                        }
                        break;
                    case "ShapeModel":
                        {
                            DialogParameters param = new DialogParameters();
                            param.Add("Parameter", project.Parameter);
                            param.Add("Image", mImage);
                            _dialogService.ShowDialog("FunctionShapeModelDialog", param, arg => {
                                if (arg.Result == ButtonResult.Yes)
                                {
                                    try
                                    {
                                        string paramer = arg.Parameters.GetValue<string>("Parameter");
                                        project.Parameter = paramer;
                                        using var mdb = new MDbContext(partNum);
                                        var _mParam = mdb.VisionProjects.FirstOrDefault(m => m.Id == project.Id);
                                        if (_mParam != null)
                                        {
                                            _mParam.Parameter = paramer;
                                            mdb.SaveChanges();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                           
                                }
                            });
                        }
                        break;
                    case "TwoLineIntersection":
                        {
                            DialogParameters param = new DialogParameters();
                            param.Add("Parameter", project.Parameter);
                            param.Add("Image", mImage);
                            _dialogService.ShowDialog("FunctionTwoLineIntersectionDialog", param, arg => {
                                if (arg.Result == ButtonResult.Yes)
                                {
                                    try
                                    {
                                        string paramer = arg.Parameters.GetValue<string>("Parameter");
                                        project.Parameter = paramer;
                                        using var mdb = new MDbContext(partNum);
                                        var _mParam = mdb.VisionProjects.FirstOrDefault(m => m.Id == project.Id);
                                        if (_mParam != null)
                                        {
                                            _mParam.Parameter = paramer;
                                            mdb.SaveChanges();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }

                                }
                            });
                        }
                        break;
                    case "NccModel":
                        {
                            DialogParameters param = new DialogParameters();
                            param.Add("Parameter", project.Parameter);
                            param.Add("Image", mImage);
                            _dialogService.ShowDialog("FunctionNccModelDialog", param, arg => {
                                if (arg.Result == ButtonResult.Yes)
                                {
                                    try
                                    {
                                        string paramer = arg.Parameters.GetValue<string>("Parameter");
                                        project.Parameter = paramer;
                                        using var mdb = new MDbContext(partNum);
                                        var _mParam = mdb.VisionProjects.FirstOrDefault(m => m.Id == project.Id);
                                        if (_mParam != null)
                                        {
                                            _mParam.Parameter = paramer;
                                            mdb.SaveChanges();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }

                                }
                            });
                        }
                        break;
                    case "BlobRectangle":
                        {
                            DialogParameters param = new DialogParameters();
                            param.Add("Parameter", project.Parameter);
                            param.Add("Image", mImage);
                            _dialogService.ShowDialog("FunctionBlobRectangleDialog", param, arg => {
                                if (arg.Result == ButtonResult.Yes)
                                {
                                    try
                                    {
                                        string paramer = arg.Parameters.GetValue<string>("Parameter");
                                        project.Parameter = paramer;
                                        using var mdb = new MDbContext(partNum);
                                        var _mParam = mdb.VisionProjects.FirstOrDefault(m => m.Id == project.Id);
                                        if (_mParam != null)
                                        {
                                            _mParam.Parameter = paramer;
                                            mdb.SaveChanges();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }

                                }
                            });
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        void ExecuteAddFunctionCommand(object obj)
        {
            DialogParameters param = new DialogParameters();
            param.Add("PartNum", partNum);
            _dialogService.ShowDialog("AddVisionFunctionDialog", param, arg =>
            {
                if (arg.Result == ButtonResult.Yes)
                {
                    var id = arg.Parameters.GetValue<int>("FuntionId");
                    try
                    {
                        if (CurProgram != null)
                        {
                            int _pcsOrder = 0;
                            using var mdb = new MDbContext(partNum);
                            if (obj == null)
                            {
                                //没选，就放在最后
                                var projects = mdb.VisionProjects.Where(project => project.ProgramId == CurProgram.Id);
                                
                                if (projects.Any())
                                {
                                    _pcsOrder = projects.Count();
                                }
                               
                            }
                            else 
                            {
                                if (obj is VisionProjectDisp selectProject)
                                {
                                    //选了,放在后面一个
                                    var projects = mdb.VisionProjects.Where(project => project.ProgramId == CurProgram.Id && project.PcsOrder > selectProject.PcsOrder);
                                    if (projects.Any())
                                    {
                                        projects.ToList().ForEach(p => {
                                            p.PcsOrder += 1;
                                        });
                                    }
                                    mdb.SaveChanges();
                                    _pcsOrder = selectProject.PcsOrder + 1;
                                }
                            }
                            string _parameter = string.Empty;
                            var fun1 = mdb.VisionFunctions.FirstOrDefault(f => f.Id == id);
                            if (fun1 != null)
                            {
                                switch (fun1.Name)
                                {
                                    case "ShapeModel":
                                        {
                                            var MShapeModelParam = new ShapeModelParam();
                                            MShapeModelParam.NumLevels = 3;
                                            MShapeModelParam.AngleStart = -10;
                                            MShapeModelParam.AngleEnd = 10;
                                            MShapeModelParam.FileName = "";
                                            MShapeModelParam.MinScore = 0.5;
                                            _parameter = JsonConvert.SerializeObject(MShapeModelParam, Formatting.Indented);
                                        }
                                        break;
                                    case "PreProcessing":
                                        {
                                            var MPreProcessingParam = new PreProcessingParam
                                            {
                                                IsUseEmphasize = false,
                                                EmphasizeMaskWidth = 7,
                                                EmphasizeMaskHeight = 7,
                                                EmphasizeFactor = 2.0
                                            };
                                            _parameter = JsonConvert.SerializeObject(MPreProcessingParam, Formatting.Indented);
                                        }
                                        break;
                                    case "BlobCircle":
                                        {
                                            var MBlobCircleParam = new BlobCircleParam();
                                            MBlobCircleParam.Row = 100;
                                            MBlobCircleParam.Column = 100;
                                            MBlobCircleParam.Radius = 80;
                                            MBlobCircleParam.MinGray = 128;
                                            MBlobCircleParam.MaxGray = 255;
                                            MBlobCircleParam.OpeningRadius = 40;
                                            MBlobCircleParam.SelectAreaMin = 10000;
                                            MBlobCircleParam.SelectAreaMax = 20000;
                                            MBlobCircleParam.SelectRadiusMin = 50;
                                            MBlobCircleParam.SelectRadiusMax = 80;
                                            _parameter = JsonConvert.SerializeObject(MBlobCircleParam, Formatting.Indented);
                                        }
                                        break;
                                    case "TwoLineIntersection":
                                        {
                                            var MTwoLineIntersectionParamDisp = new TwoLineIntersectionParam
                                            {
                                                ST_Row = 0,
                                                ST_Column = 0,
                                                L1_StartRow = 0,
                                                L1_StartColumn = 0,
                                                L1_EndRow = 10,
                                                L1_EndColumn = 10,
                                                L1_MeasureLength1 = 20,
                                                L1_MeasureLength2 = 5,
                                                L1_MeasureThreshold = 60,
                                                L1_MeasureSigma = 1,
                                                L1_MeasureSelect = MeasureSelecteEnum.first,
                                                L1_MeasureTransition = MeasureTransitionEnum.positive,
                                                L1_NumMeasures = 10,
                                                L1_MinScore = 0.4,
                                                L2_StartRow = 0,
                                                L2_StartColumn = 0,
                                                L2_EndRow = 10,
                                                L2_EndColumn = 10,
                                                L2_MeasureLength1 = 20,
                                                L2_MeasureLength2 = 5,
                                                L2_MeasureThreshold = 60,
                                                L2_MeasureSigma = 1,
                                                L2_MeasureSelect = MeasureSelecteEnum.first,
                                                L2_MeasureTransition = MeasureTransitionEnum.positive,
                                                L2_NumMeasures = 10,
                                                L2_MinScore = 0.4,
                                            };
                                            _parameter = JsonConvert.SerializeObject(MTwoLineIntersectionParamDisp, Formatting.Indented);
                                        }
                                        break;
                                    case "NccModel":
                                        {
                                            var MNccModelParam = new NccModelParam();
                                            MNccModelParam.NumLevels = 0;
                                            MNccModelParam.AngleStart = -10;
                                            MNccModelParam.AngleEnd = 10;
                                            MNccModelParam.FileName = "";
                                            MNccModelParam.MinScore = 0.5;
                                            _parameter = JsonConvert.SerializeObject(MNccModelParam, Formatting.Indented);
                                        }
                                        break;
                                    case "BlobRectangle":
                                        {
                                            var MBlobRectangleParam = new BlobRectangleParam {
                                                IsCheckNi = true,
                                                ClosingWidth = 3,
                                                SelectRecAreaMin = 1000,
                                                SelectRecAreaMax = 2000,
                                                IsCheckLasered = true,
                                                SelectLaserPadAreaMin = 500,
                                                SelectLaserPadAreaMax = 1000,
                                                ST_Row = 0,
                                                ST_Column = 0,
                                                RecRow1 = 0,
                                                RecColumn1 = 0,
                                                RecRow2 = 100,
                                                RecColumn2 = 100
                                            };
                                            _parameter = JsonConvert.SerializeObject(MBlobRectangleParam, Formatting.Indented);
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                            mdb.VisionProjects.Add(new VisionProject
                            {
                                ProgramId = CurProgram.Id,
                                FunctionId = id,
                                PcsOrder = _pcsOrder,
                                Parameter = _parameter
                            });
                            mdb.SaveChanges();
                            LoadProject(partNum, CurProgram.Id);
                        }                        
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                }
            });
        }
        void ExecuteProgramListSelectCommand(object obj)
        {
            if (obj is VisionProgramDisp prog)
            {
                CameraAppendHObject0 = null;
                CameraImage0 = null;
                CameraAppendHMessage0 = null;
                mImage = null;
                IsReady = true;
                LoadProject(partNum, prog.Id);
            }
        }
        #endregion
        #region 导航
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            partNum = parameters.GetValue<string>("PartNum");
            LoadProgram(partNum);
        }
        #endregion
        #region 构造函数
        public VisionProgramDialogViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            Title = "视觉编程";
            IsReady = false;
            //HOperatorSet.GenEmptyObj(out mImage);
            _dialogService = containerProvider.Resolve<IDialogService>();
        }
        #endregion
        #region 功能函数
        private void LoadProgram(string partNum)
        {
            ProgramList.Clear();
            IsReady = false;
            try
            {
                using var mdb = new MDbContext(partNum);
                var programs = mdb.VisionPrograms.Where(p => p.Id > 0);
                if (programs.Any())
                {
                    programs.ToList().ForEach(p =>
                    {
                        ProgramList.Add(new VisionProgramDisp { 
                            Id = p.Id,
                            Name = p.Name
                        });
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void LoadProject(string partNum,int programId)
        {
            ProjectList.Clear();
            try
            {
                using var mdb = new MDbContext(partNum);
                var projects = mdb.VisionProjects.Where(project => project.ProgramId == programId).OrderBy(p => p.PcsOrder);
                if (projects.Any())
                {
                    projects.ToList().ForEach(project =>
                    {
                        var _function = mdb.VisionFunctions.FirstOrDefault(f => f.Id == project.FunctionId);
                        ProjectList.Add(new VisionProjectDisp
                        {
                            Id = project.Id,
                            Name = _function.Name,
                            Alias = _function.Alias,
                            IconPath = Path.Join(System.AppDomain.CurrentDomain.BaseDirectory, _function.IconPath),
                            ProgramId = project.ProgramId,
                            FunctionId = project.FunctionId,
                            PcsOrder = project.PcsOrder,
                            Parameter = project.Parameter,
                            Result = DispReuslt.Unkown
                        });
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion
    }
}
